import {StyleSheet, Text, TouchableOpacity, View, TextInput, Image, ScrollView} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FormTitle from "@/components/FormTitle";
import TabCard from "@/components/TabCard";
import FcSlider from "@/components/FcSlider";
import useGetStorage from "@/hooks/useGetStorage";
import {router, useLocalSearchParams} from "expo-router";
import {Toast, Flex} from "@ant-design/react-native";
import {useDispatch, useSelector} from "react-redux";
import {set_videoList} from "@/store/reducer/videoPublish/videoPublishSlice";
import {LinearGradient} from "expo-linear-gradient";
import { useFocusEffect } from '@react-navigation/native';

import {
  useGenVideoMutation,
  useGenPictrueMutation,
  useQueryTaskStatusMutation
} from "@/store/api/videoAndPictrue/videoAndPictrueApi";

type Props = {}

const batch = (props: Props) => {
  const [tabList, setTabList] = useState([
    {
      name: '文生视频',
      val: 1,
      icon: require('@/assets/images/aiOriginality/tab_select_left.png'),
      icon1: require('@/assets/images/aiOriginality/tab_noselect_left.png'),
      style: {
        marginRight: -15,
        position: "relative",
        zIndex: 100,
      }
    }, {
      name: '文生图片',
      val: 2,
      icon: require('@/assets/images/aiOriginality/tab_noselect_right.png'),
      icon1: require('@/assets/images/aiOriginality/tab_select_right.png'),
      style: {
        marginLeft: -15,
        position: "relative",
        zIndex: 100,
      }
    }
  ])
  const [activeTab, setActiveTab] = useState(1)
  const [videoObj,setVideoObj] = useState<any>({
    prompt: '',
    aspectRatio: '9:16',
    num: 1,
    cfgScale: 0.5,
    mode: 'std',
    duration: 5,
    type: 0,
  })
  const [pictrueObj,setPictrueObj] = useState<any>({
    prompt: '',
    aspectRatio: '9:16',
    num: 1,
    cfgScale: 5,
    type: 1,
  })
  const [exampleList,setExampleList] = useState<any>([
    {
      name: '灌装机',
      prompt: '灌装工厂流水线上，一台灌装机正在灌装一瓶洗发液，特写灌装瞬间'
    },
    {
      name: '牛仔裤',
      prompt: '一个工厂女工正在缝纫机上全神贯注缝制牛仔裤，周围是裁剪好的服装面料'
    },
    {
      name: '激光打标机',
      prompt: '一台激光打标机在金属板上刻字，特写神奇的刻字过程'
    },
    {
      name: '火锅店',
      prompt: '火锅店里，几个年轻人在吃麻辣火锅，欢庆热闹的氛围'
    },
    {
      name: '美容院',
      prompt: '一个美容师在温馨房间里给顾客做spa，背后柜子上有各种精油瓶瓶罐罐'
    },
    {
      name: '早教',
      prompt: '一个35岁妈妈晚上在家辅导7岁儿子写作业，孩子很沮丧，妈妈接近崩溃边缘'
    },
    {
      name: '直播带货',
      prompt: '直播间里，一个女主播一边试衣一边对镜头讲解，全貌展现直播间灯光设施等器材'
    },
    {
      name: '熊猫',
      prompt: '一只憨态可掬的大熊猫在样阳光下惬意啃着新鲜胡萝卜'
    }
  ])
  const [isLoading, setIsLoading] = useState(false)
  const [worksObj, setWorksObj] = useState<any>({})
  
  const timer:any = useRef(null)
  
  const [genVideoFun] = useGenVideoMutation()
  const [genPictrueFun] = useGenPictrueMutation()
  const [queryTaskStatusFun] = useQueryTaskStatusMutation()

  useFocusEffect(
    React.useCallback(() => {
      return () => {
        clearInterval(timer.current)
      };
    }, [])
  );

  //AI编写
  const handleWrite = async() => {
    if((activeTab == 1 && !videoObj?.prompt) || (activeTab == 2 && !pictrueObj?.prompt)){
      Toast.info('请输入主体内容')
      return
    }

    Toast.config({ duration: 0})
    let loading = Toast.loading('AI编写中')

    await useGetStorage('token').then(async (token) => {
      try {
        const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}mm/mmViewGeneration/generationPrompt`,{
          method: 'POST',
          headers: {
            'content-type': 'application/json',
            'x-access-token': token,
          },
          body: JSON.stringify({
            mainBody: activeTab == 1 ? videoObj?.prompt : pictrueObj?.prompt,
            stream: true,
            type: activeTab == 1 ? 0 : 1
          })
        });

        const blob = await response.blob();
        const reader = new FileReader();

        reader.onload = (event:any) => {
          const result = event.target.result;
          // 按行分割流式数据
          const lines = result.split('\n');
          lines.forEach((line:any) => {
            if (line) {
              let newLine = `${line.replace('data:','')}`;
              // 在这里处理流式数据
              let res = JSON.parse(newLine)
              if (res.status == 'success') {
                let txt = res.text.replace(/(<br\/>)|(<br)/g, '');

                if(activeTab == 1){
                  setVideoObj({...videoObj, prompt: txt})
                }else{
                  setPictrueObj({...pictrueObj, prompt: txt})
                }

                if(res.stop){
                  Toast.remove(loading)
                  Toast.config({ duration: 2})
                  Toast.info('AI编写成功')
                }
              }
            }
          });
        };

        reader.onerror = (error) => {
          console.error('Error reading blob:', error);
        };

        reader.readAsText(blob);
      }catch (error) {}
    })
  }

  //生成作品
  const handleSubmit = () => {
    if((activeTab == 1 && !videoObj?.prompt) || (activeTab == 2 && !pictrueObj?.prompt)){
      return
    }

    clearInterval(timer.current)

    if(activeTab == 1){
      genVideoFun(videoObj).then(res => {
        // setIsLoading(true)
        // setWorksObj(res.data.result)

        // timer.current = setInterval(() => {
        //   handleQueryTaskStatus(res.data.result.id)
        // }, 10000)
        router.push(`/videoAndPictrue/worksAll?type=0`)
      })
    }else {
      genPictrueFun(pictrueObj).then(res => {
        // setIsLoading(true)
        // setWorksObj(res.data.result)

        // timer.current = setInterval(() => {
        //   handleQueryTaskStatus(res.data.result.id)
        // }, 10000)
        router.push(`/videoAndPictrue/worksAll?type=1`)
      })
    }
  }

  //获取作品生成状态
  const handleQueryTaskStatus = (id:any) => {
    queryTaskStatusFun({ids: id}).then(res => {
      let arr = res.data.result[0].detailList.filter((val:any) => val.taskStatus == 'submitted' || val.taskStatus == 'processing')
      if(arr.length == 0){
        handleJumpWorks(res.data.result[0].id)
      }
    })
  }

  //跳转到作品页面
  const handleJumpWorks = (id:any) => {
    setIsLoading(false)
    router.push(`/videoAndPictrue/works?id=${id}`)
  }

  //选中推荐
  const handleCheckExample = (item:any) => {
    if(activeTab == 1){
      setVideoObj({
        ...videoObj,
        prompt: item.prompt,
      })
    }else{
      setPictrueObj({
        ...pictrueObj,
        prompt: item.prompt,
      })
    }
  }


  return (
    <View style={{height: '100%'}}>
      <PageScrollView
        pageTab={
          <PageTabBar
            style={{marginVertical: 10}}
            title='文生视图'
            right={
              <TouchableOpacity style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} onPress={() => router.push(`/videoAndPictrue/worksAll?type=${activeTab == 1 ? 0 : 1}`)}>
                <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 3}}>&#xe663;</Text>
                <Text>历史生成</Text>
              </TouchableOpacity>
            }
          />
        }
        pageHeader={
          <TabCard tabList={tabList} selectVal={activeTab} onTabCardClick={(item:any) => setActiveTab(item.val)}/>
        }
        pageBottom={
          <Flex justify='center' style={{height: 56, backgroundColor: '#FFF'}}>
            {
              activeTab == 1 ?
              <FcButton
                onClick={() => handleSubmit()}
                type='BjJB'
                colors={videoObj?.prompt ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
                style={{width: '90%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='立即生成'
              />
              : 
              <FcButton
                onClick={() => handleSubmit()}
                type='BjJB'
                colors={pictrueObj?.prompt ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
                style={{width: '90%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='立即生成'
              />
            }
          </Flex>
        }
      >
        <View>
          <View style={{backgroundColor: '#FFF', paddingHorizontal: 12, borderBottomStartRadius: 8, borderBottomEndRadius: 8}}>
            <Flex justify='between'>
              <FormTitle style={{paddingVertical: 8}} title='推荐尝试'/>

              {/* <TouchableOpacity onPress={() => {}}>
                <Text style={{color: '#2856FF'}}>刷新</Text>
              </TouchableOpacity> */}
            </Flex>
            
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
            >
              {
                exampleList?.map((item:any, index:any) => (
                  <TouchableOpacity key={index} style={styles.example_item} onPress={() => handleCheckExample(item)}>
                    <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>{item.name}</Text>
                  </TouchableOpacity>
                ))
              }
            </ScrollView>
            

            <FormTitle isLeftIcon style={{paddingVertical: 8, marginTop: 8}} title='视频描述'/>
            <View style={{position: 'relative'}}>
              {
                activeTab == 1 ?
                <TextInput
                  style={[styles.desc_input, {height: 300}]}
                  multiline={true}
                  value={videoObj.prompt}
                  placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                  placeholder={'请输入主体，如人、动物、植物及物体等,根据主体名称自动生成相关场景'}
                  onChangeText={(val) => {if(videoObj.prompt.length <= 500) setVideoObj({...videoObj, prompt: val})}}
                />
                :
                <TextInput
                  style={[styles.desc_input, {height: 300}]}
                  multiline={true}
                  value={pictrueObj.prompt}
                  placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                  placeholder={'请输入主体，如人、动物、植物及物体等,根据主体名称自动生成相关场景'}
                  onChangeText={(val) => {if(pictrueObj.prompt.length <= 500) setPictrueObj({...pictrueObj, prompt: val})}}
                />
              }

              <Flex style={styles.aiwrite_box}>
                {
                  activeTab == 1 ?
                  <Text style={{fontSize: 12, color: 'rgba(0, 0, 0, 0.5)'}}>{videoObj?.prompt?.length || 0}/500</Text>
                  :
                  <Text style={{fontSize: 12, color: 'rgba(0, 0, 0, 0.5)'}}>{pictrueObj?.prompt?.length || 0}/500</Text>
                }
                <LinearGradient 
                  colors={['#6989FF', '#C65EFD']}
                  style={styles.aiwrite}
                  start={{x: 0, y: 0}}
                  end={{x: 1, y: 1}}
                  >
                  <TouchableOpacity style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} onPress={() => handleWrite()}>
                    <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#FFF', marginRight: 3}}>&#xe63d;</Text>
                    <Text style={{color: '#FFF', fontSize: 12}}>AI编写</Text>
                  </TouchableOpacity>
                </LinearGradient>
              </Flex>
            </View>
          </View>

          <View style={{padding: 12, backgroundColor: '#FFF', borderRadius: 8, marginTop: 8}}>
            {
              activeTab == 1 ?
              <View>
                <FormTitle isLeftIcon style={{paddingTop: 0, paddingBottom: 8}} title='视频比例'/>
                <Flex>
                  <FcButton
                    onClick={() => setVideoObj({...videoObj, aspectRatio: '9:16'})}
                    type={videoObj?.aspectRatio == '9:16' ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15, marginRight: 8}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='9:16'
                    borderWidth={1}
                  />

                  <FcButton
                    onClick={() => setVideoObj({...videoObj, aspectRatio: '16:9'})}
                    type={videoObj?.aspectRatio == '16:9' ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='16:9'
                    borderWidth={1}
                  />
                </Flex>

                <FormTitle 
                  title='生成数量'
                  style={{paddingBottom: 8, paddingTop: 24}}
                  isLeftIcon
                  right={
                    <View style={styles.slider_wrap}>
                      <TextInput style={styles.slider_input} value={videoObj?.num + ''}></TextInput>
                      <Text style={styles.slider_txt}>条</Text>
                    </View>
                  }
                />
                <FcSlider value={videoObj?.num} showMinMax min={1} max={4} onFcSlider={(val:any) => setVideoObj({...videoObj, num: val})}/>

                <FormTitle 
                  title='创意想象力'
                  style={{paddingBottom: 8, paddingTop: 24}}
                  isLeftIcon
                  right={
                    <View style={styles.slider_wrap}>
                      <TextInput style={styles.slider_input} value={videoObj?.cfgScale + ''}></TextInput>
                      <Text style={styles.slider_txt}>级</Text>
                    </View>
                  }
                />
                <FcSlider value={videoObj?.cfgScale} showMinMax min={0.1} max={1} step={0.1} onFcSlider={(val:any) => setVideoObj({...videoObj, cfgScale: val})}/>
              
                <FormTitle style={{paddingBottom: 8, paddingTop: 24}} isLeftIcon title='生成模式'/>
                <Flex>
                  <FcButton
                    onClick={() => setVideoObj({...videoObj, mode: 'std'})}
                    type={videoObj?.mode == 'std' ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15, marginRight: 8}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='标准'
                    borderWidth={1}
                  />

                  <FcButton
                    onClick={() => setVideoObj({...videoObj, mode: 'pro'})}
                    type={videoObj?.mode == 'pro' ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='高品质'
                    borderWidth={1}
                  />
                </Flex>

                <FormTitle style={{paddingBottom: 8, paddingTop: 24}} isLeftIcon title='生成时长'/>
                <Flex>
                  <FcButton
                    onClick={() => setVideoObj({...videoObj, duration: 5})}
                    type={videoObj?.duration == 5 ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15, marginRight: 8}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='5S'
                    borderWidth={1}
                  />

                  <FcButton
                    onClick={() => setVideoObj({...videoObj, duration: 10})}
                    type={videoObj?.duration == 10 ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='10S'
                    borderWidth={1}
                  />
                </Flex>
              </View>
              :
              <View>
                <FormTitle isLeftIcon style={{paddingTop: 0, paddingBottom: 8}} title='图片比例'/>
                <Flex>
                  <FcButton
                    onClick={() => setPictrueObj({...pictrueObj, aspectRatio: '9:16'})}
                    type={pictrueObj?.aspectRatio == '9:16' ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15, marginRight: 8}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='9:16'
                    borderWidth={1}
                  />

                  <FcButton
                    onClick={() => setPictrueObj({...pictrueObj, aspectRatio: '16:9'})}
                    type={pictrueObj?.aspectRatio == '16:9' ? 'txtJBAndBkJB' : 'default'}
                    style={{width: 100, height: 40, fontSize: 15}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='16:9'
                    borderWidth={1}
                  />
                </Flex>

                <FormTitle 
                  title='生成数量'
                  style={{paddingBottom: 8, paddingTop: 24}}
                  isLeftIcon
                  right={
                    <View style={styles.slider_wrap}>
                      <TextInput style={styles.slider_input} value={pictrueObj?.num + ''}></TextInput>
                      <Text style={styles.slider_txt}>张</Text>
                    </View>
                  }
                />
                <FcSlider value={pictrueObj?.num} showMinMax min={1} max={4} onFcSlider={(val:any) => setPictrueObj({...pictrueObj, num: val})}/>

                <FormTitle 
                  title='创意想象力'
                  style={{paddingBottom: 8, paddingTop: 24}}
                  isLeftIcon
                  right={
                    <View style={styles.slider_wrap}>
                      <TextInput style={styles.slider_input} value={pictrueObj?.cfgScale + ''}></TextInput>
                      <Text style={styles.slider_txt}>级</Text>
                    </View>
                  }
                />
                <FcSlider value={pictrueObj?.cfgScale} showMinMax min={1} max={10} onFcSlider={(val:any) => setPictrueObj({...pictrueObj, cfgScale: val})}/>
              </View>
            }
          </View>
        </View>
      </PageScrollView>

      {
        isLoading ? 
        <View style={styles.genBox}>
          <Image style={{width: 100, height: 100}} resizeMode={'contain'} source={require('@/assets/images/loading.gif')}></Image>
          <Text style={{textAlign: 'center'}}>生成中，预计需要2-5分钟，请稍候 ~退出后，AI会继续生成</Text>
          <Flex style={{width: '100%',marginTop: 30}} justify='between'>
            <TouchableOpacity style={styles.gen_btn} onPress={() => setIsLoading(false)}>
              <Text style={{lineHeight: 40, textAlign: 'center'}}>取消</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.gen_btn} onPress={() => handleJumpWorks(worksObj.id)}>
              <Text style={{lineHeight: 40, textAlign: 'center', color: '#2856FF'}}>查看生成记录</Text>
            </TouchableOpacity>
          </Flex>
        </View>
        : null
      }
    </View>
  )
}

export default batch

const styles = StyleSheet.create({
  desc_input: {
    backgroundColor: '#F1F2F4',
    color: 'rgba(0,0,0,0.9)',
    fontSize: 15,
    lineHeight: 26,
    padding: 12,
    borderRadius: 8,
    marginBottom: 12,
    textAlignVertical: 'top',
  },
  aiwrite_box: {
    position: 'absolute',
    bottom: 30,
    right: 10,
  },
  aiwrite: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    width: 80,
    height: 28,
    borderRadius: 4,
    color: '#FFF',
    marginLeft: 10,
    backgroundColor: 'linear-gradient(90deg, #6989FF 0%, #C65EFD 100%)',
  },
  slider_wrap: {
    flexDirection: "row",
    alignItems: "center",
  },
  slider_input: {
    width: 56,
    height: 32,
    textAlign: "center",
    borderRadius: 8,
    backgroundColor: '#F1F2F4'
  },
  slider_txt: {
    marginLeft: 8,
    fontSize: 14,
    color: 'rgba(0,0,0,0.5)'
  },
  genBox: {
    height: '100%',
    position: 'absolute',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: '20%',
    backdropFilter: 'blur(15px)',
  },
  gen_btn: {
    width: '48%',
    height: 40,
    backgroundColor: '#F1F2F4',
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#D8D8D8'
  },
  example_item: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    backgroundColor: '#F1F2F4',
    marginRight: 8,
    borderRadius: 20,
  }
})